#include "../include/structure.h"

int localNetFdSend(int net_fd, int local_socket_fd){

    char str[5] = {0};
    struct iovec iovs[1];
    iovs[0].iov_base = str;
    iovs[0].iov_len = sizeof(str);

    struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;
    void *p = CMSG_DATA(cms);
    int *pfd = (int *)p;
    // 真正要传的文件描述符
    *pfd = net_fd;

    struct msghdr msg;
    __bzero(&msg, sizeof(msg));
    msg.msg_iov = iovs;
    msg.msg_iovlen = 1;
    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    // 发送数据
    int ret = sendmsg(local_socket_fd, &msg, 0);
    ERROR_CHECK(ret, -1, "sendmsg");
    return 0;
}

int localNetFdRecv(int *net_fd, int local_socket_fd){


    char buf[5] = {0};
    struct iovec iovs[1];
    iovs[0].iov_base = buf;
    iovs[0].iov_len = sizeof(buf);

    struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    struct msghdr msg;
    __bzero(&msg, sizeof(msg));    
    msg.msg_iov = iovs;
    msg.msg_iovlen = 1;    
    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));
    
    int ret = recvmsg(local_socket_fd, &msg, 0);
    ERROR_CHECK(ret, -1, "recvmsg");

    void *p = CMSG_DATA(cms);
    int *p_net_fd = (int *)p;
    *net_fd = *p_net_fd;
    return 0;
}